package com.chuan.thinkingjava.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import com.sun.org.apache.xerces.internal.util.EntityResolver2Wrapper;

public class DBUtil {
	
	// JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
    static final String DB_URL = "jdbc:mysql://localhost:3306/test";
 
    // 数据库的用户名与密码，需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "admin";
    
    private static Statement stmt = null;
    
    private static Connection conn = null;
    
    {
        createConnect();
        System.out.println("Goodbye!");
    }
    
    public static void insert(String sql) throws SQLException {
		try {
			if (null == stmt) createConnect();
			stmt.execute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
    
    static void createConnect() {
    	try{
            // 注册 JDBC 驱动
            Class.forName("com.mysql.jdbc.Driver");
        
            // 打开链接
            conn = DriverManager.getConnection(DB_URL,USER,PASS);
            stmt = conn.createStatement();
        }catch(SQLException se){
            // 处理 JDBC 错误
            se.printStackTrace();
        }catch(Exception e){
            // 处理 Class.forName 错误
            e.printStackTrace();
        }
    }
    
    static void closeConnc() {
    	// 关闭资源
        try{
            if(stmt!=null) stmt.close();
        }catch(SQLException se2){
        }// 什么都不做
        try{
            if(conn!=null) conn.close();
        }catch(SQLException se){
            se.printStackTrace();
        }
    }
}
